<template>
  <div class="tester-info">
    <InfoCard :title="title" :rightText="rightText" @click-right-text="getTesterInfo">
      <template v-slot:content>
        <div class="tester-info__content">
          <div class="tester-info__text" v-if="!loading">
            <div class="tester-info__item">
              <p class="tester-info__label">仪器名称</p>
              <p class="tester-info__value">{{ name }}</p>
            </div>
            <div class="tester-info__item">
              <p class="tester-info__label">仪器型号</p>
              <p class="tester-info__value" v-if="!isNoInfo">{{ model }}</p>
              <p class="tester-info__value" v-if="isNoInfo">{{ none }}</p>
            </div>
            <div class="tester-info__item">
              <div class="tester-info__label">出厂编号</div>
              <p class="tester-info__value" v-if="!isNoInfo">{{ serialNo }}</p>
              <p class="tester-info__value" v-if="isNoInfo">{{ none }}</p>
            </div>
            <div class="tester-info__item">
              <div class="tester-info__label">版本号</div>
              <p class="tester-info__value" v-if="!isNoInfo">{{ version }}</p>
              <p class="tester-info__value" v-if="isNoInfo">{{ none }}</p>
            </div>
            <div class="tester-info__item">
              <div class="tester-info__label">仪器厂家</div>
              <p class="tester-info__value" v-if="!isNoInfo">{{ manufacturer }}</p>
              <p class="tester-info__value" v-if="isNoInfo">{{ none }}</p>
            </div>
          </div>
          <div class="tester-info__img" v-if="!loading">
            <img :src="img" alt="Tester Image" />
          </div>
          <van-loading color="#547ffb" type="spinner" v-if="loading" class="tester-info__loading">
            获取仪器信息
          </van-loading>
        </div>
      </template>
    </InfoCard>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import InfoCard from '@/components/info-card';
import { testerList } from '@/config/tester';
import eventBus, { eventNames } from '@/utils/event-bus';
import { unicodeEscapeToString, hex2String } from '@/utils';
import { writeInfoCode } from '@/modules/bluetooth';
import { relay, infrared } from '@/modules/const';
import { log, isDevelopment } from '@/utils';

@Component({
  name: 'tester-info',
  components: {
    InfoCard,
  }
})
export default class TesterInfo extends Vue {
  private none = '暂未获取';
  private title = '试验仪器';
  private rightText = '获取';
  private name = '';
  private manufacturer = '';
  private serialNo = '';
  private version = '';
  private model = '';
  private isNoInfo = true;
  private loading = false;
  private timer: number | NodeJS.Timeout = 0;

  private img = '';

  // 当前测试仪
  private get tester() {
    return this.$store.state.tester;
  }

  mounted() {
    eventBus.$on(eventNames.baseInfo, (data: string) => {
      this.analyzeData(data);
    })

    eventBus.$on(eventNames.handShake, (code: string) => {
      // 握手成功后获取测试仪信息
      if (code === '02') {
        this.$toast.fail({
          message: '设备忙碌，请先停止',
          duration: 2500
        });
        return;
      }
      this.getTesterInfo();
    })

    // 读取图片的图片和标题
    const item = testerList.find(item => item.key === this.tester);
    if (item) {
      this.img = item.image;
      this.name = item.title;
    }

    // 红外使用模拟数据
    if ([infrared].includes(this.tester)) {
      this.getTesterInfo();
    }
  }

  /**
   * 获取当前测试仪的信息
   * 机械特性使用短指令其余使用长指令
   */
  private getTesterInfo() {
    this.isNoInfo = true;
    this.loading = true;
    // 5秒后关闭加载
    this.timer = setTimeout(() => {
      if (this.loading) {
        this.loading = false;
        this.$toast('获取仪器信息超时');
      } else {
        clearTimeout(this.timer)
      }
    }, 5000);
    writeInfoCode();
  }

  /**
   * 解析数据
   */
  private analyzeData(data: string) {
    this.loading = false;
    const manufacturerHex = data.slice(2, 33 * 2);
    const arr = manufacturerHex.match(/.{1,4}/g) ?? [];
    const unicodeStr = arr.map(x => "\\u" + x.match(/.{1,2}/g)?.reverse().join("")).join("");
    log('厂家HEX', unicodeStr);
    this.manufacturer = unicodeEscapeToString(unicodeStr); // 厂家
    log('型号HEX', data.slice(33 * 2, 65 * 2));
    this.model = hex2String(data.slice(33 * 2, 65 * 2)); // 型号
    log('出厂编号HEX', data.slice(65 * 2, 97 * 2));
    this.serialNo = hex2String(data.slice(65 * 2, 97 * 2)); // 出厂编号
    // 规范版本号
    const versionHex = data.slice(97 * 2, 101 * 2);
    this.version = `${parseInt("0x" + versionHex.slice(0, 2))}.${parseInt(
      "0x" + versionHex.slice(2, 4)
    )}.${parseInt("0x" + versionHex.slice(4, 6))}.${parseInt(
      "0x" + versionHex.slice(6, 8)
    )}`;
    this.isNoInfo = false;
  }

  beforeDestroy() {
    eventBus.$off(eventNames.baseInfo);
    eventBus.$off(eventNames.handShake);
  }
}
</script>

<style scoped lang="scss">
.tester-info {
  margin: 8px;
  border: 1px solid #eee;
  border-radius: 8px;
  color: #333;
  font-size: 14px;
  line-height: 26px;

  &__content {
    position: relative;
    padding: 8px 12px;
  }

  &__text {
    padding: 0 8px;
    min-height: 120px;
  }

  &__item {
    display: flex;
    justify-content: flex-start;
  }

  &__label {
    flex-basis: 60px;
    text-align: justify;
    text-align-last: justify;
  }

  &__value {
    flex-grow: 1;
    color: #666;
    margin-left: 18px;
  }

  &__img {
    text-align: center;
    margin: 0 auto;
    position: absolute;
    top: 0;
    right: 0;
    width: 120px;
    height: 120px;
  }

  &__img img {
    width: 100%;
    height: 100%;
    object-fit: fill;
  }

  &__loading {
    height: 130px;
    line-height: 120px;
    text-align: center;
  }
}
</style>
